<?php
/**
 * Created by PhpStorm.
 * User: Auser
 * Date: 2017/5/8
 * Time: 23:54
 */

namespace Api\Terrace\Helper;

use Org\Net\Http;
use Api\Util\Helper;
use Admin\Model\UsersModel;
use Think\Cache;
class WebOathHelperBak
{
    public function webAuthorize($callbackUrl,$platform,$type,$code,$scope,$appid,$ComponentAccessTocken){
        //$appid = C('WX_APP_ID');
        //$secret = C('WX_SECRET');
        $config = C('wx_component');
        $wxComponentConfig = $config['component_config'];
        $accountUrl = C('AUTH_URL');
        $avater_path = C('AVATAR_PATH');
        if(!$code){
            $redirectUrl =   urlencode($accountUrl."Api/Terrace/compontneWebAuth?callbackUrl=".$callbackUrl.'&platform='.$platform.'&type='.$type.'&code='.$code."&scope=".$scope."&appid=".$appid);
            $requestUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" . $appid . "&redirect_uri=" .$redirectUrl. "&response_type=code&scope=".$scope."&state=OAUTH_REDIRECT&component_appid=" . $wxComponentConfig['component_appid'] . "#wechat_redirect";
            header("location:" . $requestUrl);
            exit(0);
        }else{
            if($scope == 'snsapi_base'){
                Helper::log('snsapi_base =====>');
                $get_token_url = "https://api.weixin.qq.com/sns/oauth2/component/access_token?appid=".$appid."&code=".$code."&grant_type=authorization_code&component_appid=".urlencode($wxComponentConfig['component_appid']) ."&component_access_token=".$ComponentAccessTocken;
                $res =Helper::curlRequest($get_token_url);
                $json_obj = json_decode($res,true);
                Helper::log('snsapi base result =====>'.$res);
                $token = $json_obj['access_token'];
                $openid = $json_obj['openid'];
                $unionid = $json_obj['unionid'];
                $where_w = array();
                $where_w["openid"] =  $openid;
                $weiModel = new \Admin\Model\UsersWeixinModel();
                $user_w = $weiModel->getUser($where_w);
                if(!$user_w) {
                    if($unionid){
                        Helper::log('union id exist =====>');
                        $userModel = new \Admin\Model\UsersModel();
                        $unionCondition['wx_union_id'] = $unionid;
                        if($user = $userModel->getUser($unionCondition)){
                            Helper::log('union_id user exist=======>');
                            //带有union_id的用户信息存在，则插入微信表中
                            $uid = $user['uid'];
                            $wechatData['uid'] = $uid;
                            $wechatData['wx_appid'] = $appid;
                            $wechatData['openid'] = $openid;
                            $weiModel->data($wechatData)->add();
                            $user['wx_apppid'] = $appid;
                            $user['openid'] = $openid;
                            return $user;
                        }else{
                            Helper::log('union user not exist =====>');
                            //注册一个新账号
//                            $user = $this->regNewUser($token,$openid,$callbackUrl,$platform,$appid);
                            $this->webAuthorize($callbackUrl,$platform,$type,"",'snsapi_userinfo',$appid,$ComponentAccessTocken);
                        }
                    }else{
//                        $user = $this->regNewUser($token,$openid,$callbackUrl,$platform,$appid);
                        $this->webAuthorize($callbackUrl,$platform,$type,"",'snsapi_userinfo',$appid,$ComponentAccessTocken);
                    }

//                    Helper::log(' user not exist===>');
//                    //重新调用
//                    $this->webAuthorize($callbackUrl,$platform,$type,"",'snsapi_userinfo',$appid,$ComponentAccessTocken);
                }else{
                    Helper::log(' user exist===>');
                    Helper::log(' uid===>'.$user_w['uid']);
                    $userModel = new \Admin\Model\UsersModel();
                    $uid =  $user_w['uid'];
                    $where_u = array();
                    $where_u['uid'] = $uid;
                    $user = $userModel->getUser($where_u);
                    Helper::log('befor user===>');
                    Helper::log($user);
                    if($unionid){
                        $updateData['wx_union_id'] = $unionid;
                        $condition = "uid = ".$uid;
                        $id = $userModel->where($condition)->save($updateData);
                        Helper::log('update result =====>'.$id);
                        $user['wx_union_id'] = $unionid;
                    }
                    $user['openid'] = $openid;
                    return $user;
                }
            }else{

                Helper::log('new user =====>');
                Helper::log('code =====>'.$code);

                $get_token_url = "https://api.weixin.qq.com/sns/oauth2/component/access_token?appid=".$appid."&code=".$code."&grant_type=authorization_code&component_appid=".urlencode($wxComponentConfig['component_appid']) ."&component_access_token=".$ComponentAccessTocken;
                $res =Helper::curl_request($get_token_url);
                $json_obj = json_decode($res,true);

                Helper::log('getaccess_token =====>');
                Helper::log($res);

                $token = $json_obj['access_token'];
                $openid = $json_obj['openid'];
                $where_w = array();
                $unionid = $json_obj['unionid'];
                $where_w["openid"] =  $openid;
                $weiModel = new \Admin\Model\UsersWeixinModel();
                $userModel = new \Admin\Model\UsersModel();
                // check user existence
                $user_w = $weiModel->getUser($where_w);
                if (!$user_w) {
                    // sleep
                    $num = mt_rand(1,20);
                    usleep($num*100*1000);
                    // try again to double confirm
                    $user_w = $weiModel->getUser($where_w);
                }

                if (!$user_w) {
                    $userModel = new \Admin\Model\UsersModel();
                    $unionCondition['wx_union_id'] = $unionid;
                    if($user = $userModel->getUser($unionCondition)){
                        Helper::log('union_id user exist=======>');
                        //带有union_id的用户信息存在，则插入微信表中
                        $uid = $user['uid'];
                        $wechatData['uid'] = $uid;
                        $wechatData['wx_appid'] = $appid;
                        $wechatData['openid'] = $openid;
                        $weiModel->data($wechatData)->add();
                        $user['wx_apppid'] = $appid;
                        $user['openid'] = $openid;
                    }else{
                        Helper::log('inv');
                        // now create user
                        //获取用户信息
                        $userInfoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" . $token . "&openid=" . $openid . "&lang=zh_CN";
                        $user_result =  Helper::curl_request($userInfoUrl);
                        $userObj = json_decode($user_result, true);
                        Helper::log('request wx user =====>');
                        Helper::log($user_result);

                        $d_callbackUrl= base64_decode($callbackUrl);
                        $domain = strstr($d_callbackUrl, 'fromuid=',true);
                        $total = strlen($d_callbackUrl);
                        $prefix = strlen($domain);
                        $referer_uid = 0;

                        if($prefix != 0){
                            $prefix = strlen($domain)+8;
                            $referer_uid = substr($d_callbackUrl,$prefix);
                        }
                        if (strlen(trim($userObj['nickname'])) == 0) {
                            // no nickname? using default one
                            $userObj['nickname'] = '茄子粉';
                        }

                        $data = array();
                        $username = $userObj['nickname'];
                        if($userModel->check_username($username)){
                            $username .= '_' . rand(1, 999);
                        }
                        $data['user_name'] = $username;
                        $data['password'] = md5(rand(111111, 999999999));
                        //$data['avatar_file'] = $userObj['headimgurl'];
                        $data['referer_uid'] = $referer_uid;
                        $data['referer_url'] = $d_callbackUrl;
                        $data['sex'] = $userObj['sex'];
                        $data['province'] = $userObj['province'];
                        $data['city'] = $userObj['city'];
                        $data['country'] = $userObj['country'];
                        $data['reg_time'] = time();
                        $data['from_type'] = 'weixin';
                        $data['from_platform'] = $platform;
                        //增加第三方平台来源字段
                        $data['from_appid'] = $appid;
                        $data['wx_union_id'] = $userObj['unionid'];
                        $uid = $userModel->data($data)->add();
                        $data_w['openid'] = $openid;
                        $data_w['uid'] = $uid;
                        $data_w['wx_appid'] = $appid;
                        $weiModel->data($data_w)->add();

                        $rootPath = realpath(__ROOT__).$avater_path;
                        $path = $rootPath.$userModel->get_avatar($uid,'real',1);
                        Helper::mkDirs($path);

                        $avatar_url = str_replace('wx.qlogo.cn', '180.163.26.115', $userObj['headimgurl']);
                        Http::curlDownload($avatar_url,$path.$userModel->get_avatar($uid,'real',2).'.jpg');
                        $image = new \Think\Image();
                        $size = filesize($path.$userModel->get_avatar($uid,'real',2).'.jpg');
                        if($size > 0){
                            $image->open($path.$userModel->get_avatar($uid,'real',2).'.jpg');
                            $image->thumb(100, 100,\Think\Image::IMAGE_THUMB_CENTER)->save($rootPath.$userModel->get_avatar($uid,'max',0).'.jpg');
                            $image->thumb(50, 50,\Think\Image::IMAGE_THUMB_CENTER)->save($rootPath.$userModel->get_avatar($uid,'mid',0).'.jpg');
                            $image->thumb(32, 32,\Think\Image::IMAGE_THUMB_CENTER)->save($rootPath.$userModel->get_avatar($uid,'min',0).'.jpg');
                            $updateData = array();
                            $avatar_file = $userModel->get_avatar($uid,'min',0).'.jpg';
                            $updateData['uid'] = $uid;
                            $updateData['avatar_file'] = $avatar_file;
                            $r = $userModel->save($updateData);
                        }
                    }
                } else {
                    $uid = $user_w['uid'];
                }

                $where_u = array();
                $where_u['uid'] = $uid;
                $user = $userModel->getUser($where_u);
                Helper::log("total_user_info============>");
                Helper::log($user);
                $user['openid'] = $openid;

                return $user;

            }
        }
    }


    protected function regNewUser($token,$openid,$callbackUrl,$platform,$appid){
        $userInfoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" . $token . "&openid=" . $openid . "&lang=zh_CN";
        $user_result =  Helper::curl_request($userInfoUrl);
        $userObj = json_decode($user_result, true);
        Helper::log('reg new user  =====>');
        Helper::log($user_result);

        $d_callbackUrl= base64_decode($callbackUrl);
        $domain = strstr($d_callbackUrl, 'fromuid=',true);
        $total = strlen($d_callbackUrl);
        $prefix = strlen($domain);
        $referer_uid = 0;

        if($prefix != 0){
            $prefix = strlen($domain)+8;
            $referer_uid = substr($d_callbackUrl,$prefix);
        }
        if (strlen(trim($userObj['nickname'])) == 0) {
            // no nickname? using default one
            $userObj['nickname'] = '茄子粉';
        }

        $userModel = new \Admin\Model\UsersModel();
        $data = array();
        $username = $userObj['nickname'];
        if($userModel->check_username($username)){
            $username .= '_' . rand(1, 999);
        }
        $data['user_name'] = $username;
        $data['password'] = md5(rand(111111, 999999999));
        //$data['avatar_file'] = $userObj['headimgurl'];
        $data['referer_uid'] = $referer_uid;
        $data['referer_url'] = $d_callbackUrl;
        $data['sex'] = $userObj['sex'];
        $data['province'] = $userObj['province'];
        $data['city'] = $userObj['city'];
        $data['country'] = $userObj['country'];
        $data['reg_time'] = time();
        $data['from_type'] = 'weixin';
        $data['from_platform'] = $platform;
        //增加第三方平台来源字段
        $data['from_appid'] = $appid;
        $data['wx_union_id'] = $userObj['unionid'];
        $uid = $userModel->data($data)->add();

        //插入微信数据
        $weiModel = new \Admin\Model\UsersWeixinModel();
        $data_w['openid'] = $openid;
        $data_w['uid'] = $uid;
        $data_w['wx_appid'] = $appid;
        $weiModel->data($data_w)->add();
        $avater_path = C('AVATAR_PATH');
        $rootPath = realpath(__ROOT__).$avater_path;
        $path = $rootPath.$userModel->get_avatar($uid,'real',1);
        Helper::mkDirs($path);

        $avatar_url = str_replace('wx.qlogo.cn', '180.163.26.115', $userObj['headimgurl']);
        Http::curlDownload($avatar_url,$path.$userModel->get_avatar($uid,'real',2).'.jpg');
        $image = new \Think\Image();
        $size = filesize($path.$userModel->get_avatar($uid,'real',2).'.jpg');
        if($size > 0){
            $image->open($path.$userModel->get_avatar($uid,'real',2).'.jpg');
            $image->thumb(100, 100,\Think\Image::IMAGE_THUMB_CENTER)->save($rootPath.$userModel->get_avatar($uid,'max',0).'.jpg');
            $image->thumb(50, 50,\Think\Image::IMAGE_THUMB_CENTER)->save($rootPath.$userModel->get_avatar($uid,'mid',0).'.jpg');
            $image->thumb(32, 32,\Think\Image::IMAGE_THUMB_CENTER)->save($rootPath.$userModel->get_avatar($uid,'min',0).'.jpg');
            $updateData = array();
            $avatar_file = $userModel->get_avatar($uid,'min',0).'.jpg';
            $updateData['uid'] = $uid;
            $updateData['avatar_file'] = $avatar_file;
            $r = $userModel->save($updateData);
        }

        $where_u = array();
        $where_u['uid'] = $uid;
        $user = $userModel->getUser($where_u);
        Helper::log("total_user_info============>");
        Helper::log($user);
        $user['openid'] = $openid;
        return $user;
    }

}